package com.example.canhui01li.myapprxretrofitdagger;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.example.canhui01li.myapprxretrofitdagger.model.UserInfo;
import com.google.gson.reflect.TypeToken;
import com.lch.base.http.callback.RxCommonCallback;
import com.lch.base.http.callback.RxResultCallBack;
import com.lch.base.http.HttpUtils;
import com.lch.base.http.exception.ApiException;
import com.lch.base.http.interfaces.HeadersInterceptor;
import com.lch.base.http.interfaces.ParamsInterceptor;
import com.example.canhui01li.myapprxretrofitdagger.model.BaseInfo;
import com.lch.base.http.model.result.BaseResult;
import com.lch.base.view.BaseActivity;

import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.reactivex.disposables.CompositeDisposable;

import static com.example.canhui01li.myapprxretrofitdagger.R.id.get_Common_String;

public class MainActivity extends BaseActivity implements View.OnClickListener {
    View mGet_BaseResult_T;
    View mGet_BaseResult_List_T;
    View mGet_Common_String;
    View mGet_Common_Model;

    Button mBtnGet, mBtnPost, mBtnPostJson, mBtnPostMulti;

    //********
    //http://www.jcodecraeer.com/plus/view.php?aid=7957 重要 。需要修改DisposableObserver，，其他地方也统一改造
    private CompositeDisposable mCompositeDisposable = new CompositeDisposable();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Log.i("lch", "BuildConfig.DEBUG22:" + BuildConfig.DEBUG);
        setContentView(R.layout.activity_main);
        initView();

//        Observable.interval(0, 1, TimeUnit.SECONDS)
//                .filter(new Predicate<Long>() {
//                    @Override
//                    public boolean test(Long aLong) throws Exception {
//                        Log.i("lch", "filter:----------------------------");
//                        return true;
//                    }
//                })
//                .subscribeOn( Schedulers.io())
//                .compose(this.<Long>bindToLifecycle())   //当Activity执行Onstop()方法是解除订阅关系
//                .observeOn( AndroidSchedulers.mainThread())
//                .subscribe(new Observer<Long>() {
//                    @Override
//                    public void onSubscribe(Disposable d) {
//                        Log.i("lch", "onSubscribe:----------------------------");
//                        mCompositeDisposable.add(d);
//                    }
//
//                    @Override
//                    public void onNext(Long aLong) {
//                        Log.i("lch", "onNext:----------------------------");
//                    }
//
//                    @Override
//                    public void onError(Throwable e) {
//
//                    }
//
//                    @Override
//                    public void onComplete() {
//
//                    }
//                });


        ParamsInterceptor mParamsInterceptor = new ParamsInterceptor() {
            @Override
            public Map checkParams(Map params) {
                //追加统一参数
                params.put("app_type", "android_price");
                return params;
            }
        };
        HeadersInterceptor mHeadersInterceptor = new HeadersInterceptor() {
            @Override
            public Map checkHeaders(Map headers) {
                //追加统一header，例：数据缓存一天
                headers.put("Cache-Time", "3600*24");
                return headers;
            }
        };


        HashMap<String, String> errorCodeMap = new HashMap<>();
        errorCodeMap.put("111", "测试错误sss");

        HttpUtils.builderConfig(getApplicationContext(), "http://www.sojson.com/", BuildConfig.DEBUG)
//                .versionApi("")//API版本，不传不可以追加接口版本号
//                .addServerUrl("")//备份服务器ip地址，可多次调用传递
//                .addCallFactory()//不传默认StringConverterFactory
//                .addConverterFactory()//不传默认RxJavaCallAdapterFactory
//                .setClient()//OkHttpClient,不传默认OkHttp3
                .setParamsInterceptor(mParamsInterceptor)//不传不进行参数统一处理
                .setHeadersInterceptor(mHeadersInterceptor)//不传不进行headers统一处理
                .setErrorCodeMap(errorCodeMap)
                .build();
    }

    public void initView() {
        mGet_BaseResult_T = findViewById(R.id.get_BaseResult_T);
        mGet_BaseResult_T.setOnClickListener(this);

        mGet_BaseResult_List_T = findViewById(R.id.get_BaseResult_List_T);
        mGet_BaseResult_List_T.setOnClickListener(this);

        mGet_Common_String = findViewById(get_Common_String);
        mGet_Common_String.setOnClickListener(this);

        mGet_Common_Model = findViewById(R.id.get_Common_Model);
        mGet_Common_Model.setOnClickListener(this);


        mBtnGet = (Button) findViewById(R.id.btn_get);
        mBtnGet.setOnClickListener(this);
        mBtnPost = (Button) findViewById(R.id.btn_post);
        mBtnPost.setOnClickListener(this);
        mBtnPostJson = (Button) findViewById(R.id.btn_post_json);
        mBtnPostJson.setOnClickListener(this);
        mBtnPostMulti = (Button) findViewById(R.id.btn_post_multi);
        mBtnPostMulti.setOnClickListener(this);
    }


    @Override
    public void onClick(View v) {
        if (v == mGet_BaseResult_T) {
            get_BaseResult_T();
        }

        if (v == mGet_BaseResult_List_T) {
            get_BaseResult_LIST_T();
        }

        if (v == mGet_Common_String) {
            get_Common_String();
        }

        if (v == mGet_Common_Model) {
            get_Common_Model();
        }

        if (v == mBtnPost) {
            testPost();
        }

        if (v == mBtnPostJson) {
            testPostJson();
        }

        if (v == mBtnPostMulti) {
            testPostMulti();
        }
    }


    /**
     * BaseResult<T>结构
     * {
     * "code": 1,
     * "msg": "接口返回测试----请求成功！！！！",
     * "data": {
     * "id": 1,
     * "name": "小猪xT",
     * "age": "30"
     * }
     * }
     */
    private void get_BaseResult_T() {
        String url = "https://xiaozhu.com/BaseResult_T";
        TestGetParams params = new TestGetParams();
        HttpUtils.get(this, url, params, this, new RxResultCallBack<UserInfo>() {

            @Override
            public void onSuccess(UserInfo data) {
                Log.e("lch1", "testBaseResultT name---------:" + data.name);
            }

            @Override
            public void onFail(ApiException e) {
                Toast.makeText(MainActivity.this, e.getMsg(), Toast.LENGTH_SHORT).show();
            }
        });

//        HttpUtils.get(this, url, params, this, null);
    }

    /**
     * BaseResult<List<T>>结构
     * Map<String, List<UserInfo>> 这种复杂结构也是完美解决 good
     * {
     * "code": 1,
     * "msg": "接口返回测试----请求成功1！！！！",
     * "data": [
     * {
     * "id": 1,
     * "name": "小猪1",
     * "age": "31"
     * },
     * {
     * "id": 2,
     * "name": "小猪2",
     * "age": "32"
     * }
     * ]
     * }
     */
    private void get_BaseResult_LIST_T() {
        String url = "http://xiaozhu.com/BaseResult_LIST_T";
        TestGetParams params = new TestGetParams();
        HttpUtils.get(this, url, params, this, new RxResultCallBack<List<UserInfo>>() {

            @Override
            public void onSuccess(List<UserInfo> data) {
                if (data != null) {
                    Log.e("lch1", "get_BaseResult_LIST_T size---------:" + data.size());
                    if (data.size() > 0) {
                        Log.e("lch1", "get_BaseResult_LIST_T name---------:" + data.get(0).name);
                    }
                }
            }

            @Override
            public void onFail(ApiException e) {
                super.onFail(e);
                Log.e("lch1", "get_BaseResult_LIST_T onFail---" + e.getCode());
                Log.e("lch1", "get_BaseResult_LIST_T onFail---" + e.getMsg());
                Toast.makeText(MainActivity.this, e.getMsg(), Toast.LENGTH_SHORT).show();
            }
        });
    }

    /**
     * String 类型
     */
    private void get_Common_String() {
//        String url = "http://demo.phalapi.net/?service=User.getBaseInfo&user_id=1";
        String url = "  https://kyfw.12306.cn/otn/";
        long timeTag = System.currentTimeMillis();
        HttpUtils.get(this, url, null, this, new RxCommonCallback<String>(timeTag) {

            @Override
            public void onSuccess(Object tag, String data) {
                Log.e("lch1", "get_Common_String tag---------:" + tag);
                Log.e("lch1", "get_Common_String data---------:" + data);
            }
        });
    }

    /**
     * 自定义model 类型
     */
    private void get_Common_Model() {
        String url = "http://xiaozhu.com/BaseResult_T";
        TestGetParams params = new TestGetParams();
        HttpUtils.get(this, url, params, this, new RxCommonCallback<BaseResult<UserInfo>>() {

            @Override
            public void onSuccess(BaseResult<UserInfo> data) {
                Log.e("lch1", "testBaseResultT name--------- :" + data.data.name);
            }
        });
    }


    public void testPost() {
        String url = "http://120.79.0.114:8082/api/login";
        TestPostParams params = new TestPostParams();

        Type type = new TypeToken<BaseResult<BaseInfo>>() {
        }.getType();
        HttpUtils.request(url, params)
//                .setType(type)
                .bindToLifecycle(this) //绑定生命周期
//                .callback(new APICallback<BaseInfo>() {
//                    @Override
//                    public void onSuccess(BaseInfo data) {
//                        Log.e("lch1", "token---------:" + data.token);
//                    }
//
//                    @Override
//                    public void onFailed(APIStatus status) {
//                        Log.e("lch1", "getMessage---------:" + status.getMessage());
//                    }
//                })
                .post();
    }


    public void testPostJson() {
        String url = "http://120.79.0.114:8082/api/login";
        TestPostJson params = new TestPostJson();

        Type type = new TypeToken<BaseResult<BaseInfo>>() {
        }.getType();
        HttpUtils.request(url, params)
//                .setType(type)
                .bindToLifecycle(this) //绑定生命周期
//                .callback(new APICallback<BaseInfo>() {
//                    @Override
//                    public void onSuccess(BaseInfo data) {
//                        Log.i("lch1", "token---------:" + data.token);
//                    }
//
//                    @Override
//                    public void onFailed(APIStatus status) {
//                        Log.e("lch1", "getMessage---------:" + status.getMessage());
//                    }
//                })
                .post();
    }


    public void testPostMulti() {
        String url = "http://120.79.0.114:8082/api/login";
        TestPostMultiParams params = new TestPostMultiParams();

        Type type = new TypeToken<BaseResult<BaseInfo>>() {
        }.getType();
        HttpUtils.request(url, params)
//                .setType(type)
                .bindToLifecycle(this) //绑定生命周期
//                .callback(new APICallback<BaseInfo>() {
//                    @Override
//                    public void onSuccess(BaseInfo data) {
//                        Log.i("lch1", "token---------:" + data.token);
//                    }
//
//                    @Override
//                    public void onFailed(APIStatus status) {
//                        Log.e("lch1", "getMessage---------:" + status.getMessage());
//                    }
//                })
                .post();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        mCompositeDisposable.clear();
    }

}
